/**
 * jQuery.timers - Timer abstractions for jQuery Written by Blair Mitchelmore
 * (blair DOT mitchelmore AT gmail DOT com) Licensed under the WTFPL
 * (http://sam.zoy.org/wtfpl/). Date: 2009/10/16
 * 
 * @author Blair Mitchelmore
 * @version 1.2 String Time Parsing
 * 
 * Example
 * 
 * $("#close-button").click(function() { $(this).oneTime(1000, function() {
 * $(this).parent(".main-window").hide(); }); });
 * $("#cancel-button").click(function() { $("#close-button").stopTime(); });
 * 
 * Timing Labels
 * 
 * Because jQuery timers connects timers to elements, it is advantageous to
 * allow for a filtration of timers prior to cancelling, in case some other
 * section of code is using jQuery timers for a different feature. Labels serve
 * this purpose by allowing the programmer to assign a specific event a specific
 * label. Labels are also automatically generated based on the timeout value of
 * the timer if no specific label is generated. This means, you can cancel all
 * timers originally set to activate 1000 ms later. This is merely a shortcut
 * for programmers who prefer convention and implicit rules. Example
 * 
 * $("#close-button").click(function() { $(this).oneTime(1000, "hide",
 * function() { $(this).parent(".main-window").hide(); }); });
 * $("#cancel-button").click(function() { $("#close-button").stopTime("hide");
 * });
 * 
 * Limited Timers
 * 
 * Limited Timers are a natural extension of the basic setTimeout/setInterval
 * pair. Rather than limiting the programmer to one event or an unending chain
 * of events, jQuery timers allows you to specify a specific number of times for
 * the event to occur. This may be useful for pseudo-asynchronous looping and
 * other time-related events. Example
 * 
 * var times = chunks.length; $(document).everyTime(1000, function(i) {
 * processChunk(i); }, times);
 * 
 * String Time Parsing
 * 
 * By default, setTimeout and setInterval take a millisecond count, but as human
 * we tend to think in seconds. So if a string is provided as the
 * interval/timeout in jQuery timers it will be parsed for standard time
 * prefixes. So "2s" means 2 seconds, "250ms" means 250 milliseconds and so
 * forth. The list of supported prefixes is larger than should ever be used.
 * Methods added to the jQuery chain everyTime(interval : Integer | String,
 * [label = interval : String], fn : Function, [times = 0 : Integer])
 * 
 * everyTime will add the defined function (fn) as a timed event to run at a
 * given time interval (interval) for a given number of times (times). If times
 * is set to 0, the number of times the method is called is unbounded. A label
 * is also set for the given timed event either to the provided string (label)
 * or to the string representation of the interval provided. Additionally, the
 * interval can be defined by using a string such as "3s" for 3 seconds.
 * oneTime(interval : Integer | String, [label = interval : String], fn :
 * Function)
 * 
 * oneTime will call the defined function (fn) a certain amount of time
 * (interval) after being added to the elements in the jQuery object. A label
 * (label) is also set for the timed event either to the provided string (label)
 * or to the string representation of the interval provided. stopTime([label :
 * Integer | String], [fn : Function])
 * 
 * stopTime will stop any timed events with the provided label (label) and
 * function (fn). If neither is specified, it will stop all timed events acting
 * on the elements in the jQuery object. If only the function is provided, then
 * it will stop all timed events calling that function regardless of label.
 * Finally if only the label is provided, it will stop all timed events given
 * that label at initialization.
 */

jQuery.fn.extend( {
	everyTime : function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime : function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime : function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend( {
	timer : {
		global : [],
		guid : 1,
		dataKey : "jQuery.timer",
		regex : /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers : {
			// Yeah this is major overkill...
			'ms' : 1,
			'cs' : 10,
			'ds' : 100,
			's' : 1000,
			'das' : 10000,
			'hs' : 100000,
			'ks' : 1000000
		},
		timeParse : function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add : function(element, interval, label, fn, times) {
			var counter = 0;

			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval;
			}

			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0)
				times = 0;

			times = times || 0;

			var timers = jQuery.data(element, this.dataKey)
					|| jQuery.data(element, this.dataKey, {});

			if (!timers[label])
				timers[label] = {};

			fn.timerID = fn.timerID || this.guid++;

			var handler = function() {
				if ((++counter > times && times !== 0)
						|| fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};

			handler.timerID = fn.timerID;

			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,
						interval);

			this.global.push(element);

		},
		remove : function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;

			if (timers) {

				if (!label) {
					for (label in timers)
						this.remove(element, label, fn);
				} else if (timers[label]) {
					if (fn) {
						if (fn.timerID) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label]) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}

					for (ret in timers[label])
						break;
					if (!ret) {
						ret = null;
						delete timers[label];
					}
				}

				for (ret in timers)
					break;
				if (!ret)
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});